package com.tang.common.context;

import com.tang.common.exception.ServiceException;

import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

public class LoginContextHolder {
    private static InheritableThreadLocal<Map<String, Object>> THREAD_LOCAL = new InheritableThreadLocal<>();

    /**
     * 获取map
     *
     * @return java.util.Map<java.lang.String, java.lang.Object>
     * @author Tang
     * @date 2024/2/20 19:14
     **/
    public static Map<String, Object> getMap() {
        Map<String, Object> map = THREAD_LOCAL.get();
        if (Objects.isNull(map)) {
            return newMap();
        }
        return map;
    }

    /**
     * 添加新值到map
     *
     * @param key   键值
     * @param value 值
     * @author Tang
     * @date 2024/2/20 19:15
     **/
    public static void set(String key, String value) {
        Map<String, Object> map = getMap();
        if (Objects.isNull(key)) {
            throw new ServiceException("key值不能为空");
        }
        map.put(key, value);
    }

    /**
     * 获取值
     *
     * @param key 键值
     * @return java.lang.Object
     * @author Tang
     * @date 2024/2/20 19:17
     **/
    public static Object get(String key) {
        Map<String, Object> map = getMap();
        return map.get(key);
    }

    /**
     * 删除ThreadLocal中的map
     *
     * @author Tang
     * @date 2024/2/20 19:18
     **/
    public static void remove() {
        THREAD_LOCAL.remove();
    }

    /**
     * 创建新的map
     *
     * @return java.util.Map
     * @author Tang
     * @date 2024/2/20 19:13
     **/
    private static Map<String, Object> newMap() {
        Map<String, Object> map = new ConcurrentHashMap<>();
        THREAD_LOCAL.set(map);
        return map;
    }

    private LoginContextHolder() {
    }
}
